package top.xana.acg.common.network

import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import top.xana.acg.common.factory.Factory
import java.util.concurrent.TimeUnit

/**
 * 网络请求封装
 */

val reMap = HashMap<String, Retrofit>()
object RetrofitImpl {
    lateinit var ins: RetrofitImpl

    fun getRetrofit(server: String): Retrofit {
        if (reMap.containsKey(server)) return reMap[server]!!
        val client = OkHttpClient.Builder()
            .addInterceptor {
                it.proceed(it.request().newBuilder().build())
            }.apply {
                connectTimeout(30, TimeUnit.SECONDS)
                readTimeout(30, TimeUnit.SECONDS)
                writeTimeout(30, TimeUnit.SECONDS)
            }.build()
        val retrofit = Retrofit.Builder().apply {
            baseUrl(server)
            client(client)
            addCallAdapterFactory(CoroutineCallAdapterFactory())
            addConverterFactory(GsonConverterFactory.create(Factory.getGson()))
        }.build()

        return retrofit
    }

    fun <T> getApi(server: String, clz: Class<T>) = getRetrofit(server).create(clz)


}